package pres.liko.iot.sdk.service.impl.impl;

import io.github.pnoker.common.constant.ValueConstant;
import io.github.pnoker.common.model.Point;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import pres.liko.iot.sdk.bean.driver.DriverContext;
import pres.liko.iot.sdk.service.DriverService;

/**
 * @ClassName: DriverServiceImpl
 * @Auther: liko
 * @Description:
 * @Date: 2022/11/7 19:49
 */
@Service
public class DriverServiceImpl implements DriverService {
 
    private DriverContext driverContext;

    @Override
    public String convertValue(String devicedId, String pointId, String rawString) {
        // 获取位号的定义对象
        Point point = driverContext.getPointByDeviceIdAndPointId(devicedId, pointId);
        switch (point.getType()) {
            // 根据类型来决定如何转换
            case ValueConstant
                    .Type.STRING:
                return rawString;
            case ValueConstant.Type.INT:
            case ValueConstant.Type.BYTE:
            case ValueConstant.Type.SHORT:
            case ValueConstant.Type.LONG:
            case ValueConstant.Type.DOUBLE:
            case ValueConstant.Type.FLOAT:
                // 先转成数数字，转成double
                Double temp = Double.parseDouble(rawString);
                if (point.getMinimum() != null && temp < point.getMinimum()) {
                    //当前传递的值小于最小值
                    System.out.println("当前传递的值小于最小值");
                    return null;
                }
                if (point.getMaximum() != null && temp > point.getMaximum()) {
                    System.out.println("当前传递的值大于最大值");
                    return null;
                }
                if (StringUtils.hasText(point.getFormat())) {
                    // 自定义格式化类型
                    return String.format(point.getFormat(), temp);
                } else {
                    return String.valueOf(temp);
                }
            case ValueConstant.Type.BOOLEAN:
                // 大于0为true,小于0为false
                if (Double.parseDouble(rawString) > 0) {
                    return Boolean.TRUE.toString();
                } else {
                    return Boolean.FALSE.toString();
                }
        }
        return null;
    }
}
